/* 
 * Execute program parallelly, mostly for benchmarking use
 * 
 * Author: Ray Will
 * Email: hustos@qq.com
 */

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *myfunc(void *v)
{
	char *exe = (char *)v;
	
	printf("thread %d started\n", (int)pthread_self());
	
	/* call external program */
	system(exe);

	printf("thread %d ended\n", (int)pthread_self());
	return NULL;
}

void usage(char **argv)
{
	printf("This tool create num_threads to run external exe_name program parallelly\n"); 
	printf("%s num_threads exe_name\n", argv[0]);
	printf("for example:%s 8 date\n", argv[0]);
	exit(0);
}


int main(int argc, char **argv)
{
	int i,n;
	pthread_t *pids;

	if (argc != 3)
	{
		usage(argv);
	}
	n = atoi(argv[1]);
	if (n <= 0)
	{
		usage(argv);
	}

	pids = (pthread_t *)malloc(n * sizeof(pthread_t));
	for (i = 0; i < n; i++)
	{
		pthread_create(&pids[i], NULL, myfunc, argv[2]);
	}
	for (i = 0; i < n; i++)
	{
		pthread_join(pids[i], NULL);
	}       
	return 0;
}
